<template>
	<view class="text-white">
		<z-paging ref="paging" @query="getList" v-model="listRaw" :auto="false">
			<template #top>
				<yTabsCase :list="categoryList" @change="onChange()" v-model="categoryId" field="id" />
			</template>

			<view class="flex gap-5 p-5">
				<view class="flex-1" v-for="(col, colIndex) in waterfallColumns" :key="colIndex">
					<view v-for="(item, index) in col" :key="index"
						class="w-p-100 round-12 overflow-hidden bg-black-1 mb-5"
						@click="$page.open('/pages/works/case-detail?id='+item.id)">
						<image :src="item.image_url" v-if="item.image_url" class="w-p-100" mode="widthFix"
							@load="onImageLoad(colIndex, index)"></image>
						<view class="p-4">
							<text class="fs-14">{{ item.prompt }}</text>
						</view>
					</view>
				</view>
			</view>
		</z-paging>
	</view>
</template>

<script setup>
	import { onMounted, ref, nextTick } from 'vue'
	import { $http, $page } from '@/utils'
	import useZPaging from '@/uni_modules/z-paging/components/z-paging/js/hooks/useZPaging.js'
	import yTabsCase from './modules/y-tabs-case.vue'

	const paging = ref(null)
	useZPaging(paging)

	const categoryList = ref([])
	const categoryId = ref(0)

	// 原始列表数据（分页加载）
	const listRaw = ref([])

	// 瀑布流列数据（二维数组）
	const waterfallColumns = ref([
		[],
		[]
	]) // 两列

	// 每列高度记录
	const columnHeights = ref([0, 0])

	// 获取分类
	const getCategory = () => {
		$http.get('Case/getCaseCategory').then(res => {
			categoryList.value = res.data
			categoryId.value = categoryList.value[0].id
			paging.value.reload()
		})
	}

	// 获取分页数据
	const getList = (page, limit) => {
		uni.showLoading({
			title: '请稍后...'
		})
		$http.get('Case/getCaseList', { page, limit, category_id: categoryId.value }).then(async res => {
			if (page == 1) {
				columnHeights.value = [0, 0]
				listRaw.value = [];
				waterfallColumns.value = [
					[],
					[]
				]
			}
			const newData = res.data
			await appendToWaterfall(newData)
			paging.value.complete(newData)
		})
	}

	// 将新数据分配到最矮列
	const appendToWaterfall = async (newData) => {
		await nextTick()
		newData.forEach(item => {
			const minIndex = columnHeights.value.indexOf(Math.min(...columnHeights.value))
			waterfallColumns.value[minIndex].push(item)
			columnHeights.value[minIndex] += 1
		})
	}

	// 图片加载后重新测量高度
	const onImageLoad = (colIndex, index) => {
		// 可在此做真实高度测量（如果想要更精准的分布）
		// uni.createSelectorQuery() + boundingClientRect() 获取高度修正
	}


	const onChange = () => {
		columnHeights.value = [0, 0]
		listRaw.value = [];
		waterfallColumns.value = [
			[],
			[]
		]
		paging.value.reload()
	}
	onMounted(() => {
		getCategory()
	})
</script>

<style scoped>
	/* 简单样式调整 */
	.w-p-100 {
		width: 100%;
	}

	.bg-black-1 {
		background-color: rgba(255, 255, 255, 0.05);
	}
</style>